const dbUtil = require('../model/dbUtil');
const dateformat = require('dateformat');

//首页
async function doIndex(req, res) {
    let sql = `select gs.g_id,gs.g_name,gs.g_desc,gs.g_price,gs.g_show_img,gs.g_stat,gc.g_sales 
                from goods gs,good_attr ga,good_count gc 
                where gs.g_id=ga.g_id 
                and gs.g_stat='Y'
                and ga.attr_id=gc.attr_id limit 0,15;`;
    let params = [];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result);
    if (result.length > 0) {
        res.render('index', { data: result });
    } else {
        res.render('index', {});
    }
}

//商品搜索
async function doSearch(req, res) {
    let { g_desc } = req.query;

    let sql = `select gs.*,gc.* 
                from goods gs,good_attr ga,good_count gc 
                where gs.g_id=ga.g_id 
                and ga.attr_id=gc.attr_id
                and gs.g_stat='Y'
                and gs.g_desc like ?`;

    let params = [`%${g_desc}%`];
    let result = await dbUtil.asyncQuery(sql, params);
    if (result.length > 0) {
        // console.log(result);
        res.render('good-list', { goodList: result, total: result.length, queryChar: g_desc });
    }
}

//商品详情
async function doGoodInfo(req, res) {
    let { g_id } = req.query;
    // console.log(g_id);
    let sql = `SELECT * from goods gs,good_attr ga,good_count gc
                where gs.g_id=ga.g_id 
                and ga.attr_id=gc.attr_id
                and gs.g_id=?`;
    let params = [g_id];
    let result = await dbUtil.asyncQuery(sql, params);
    // console.log(result[0]);
    if (result.length > 0) {
        //将商品的属性格式一下
        result[0].attr_item = result[0].attr_item.split('&');
        // console.log(result[0]);

        //查询商品评论表
        let sql = `select * from users us,good_comment gc
                    where us.user_id = gc.user_id 
                    and g_id=?`;
        let params = [g_id];
        let goodComment = await dbUtil.asyncQuery(sql, params);
        // console.log(goodComment);

        res.render('good-info', {
            data: result[0],
            commonTotal: goodComment.length, //总评论
            goodComment, //当前商品全部评论
            dateformat //时间格式化函数
        });
    } else {
        res.render('good-info', {});
    }
}

//加入商品加入购物车
async function doAddCart(req, res) {
    if (!req.session.currentUser || req.session.currentUser.userRole == 'admin') {
        res.send({ code: 400, message: "用户信息失效,请重新登录！" })
    }
    // if (req.session.currentUser && req.session.currentUser.userRole == 'admin') {
    //     res.send({ code: 400, message: "用户信息失效,请重新登录！" })
    // }

    let { uid } = req.session.currentUser;
    let { g_id, g_count, g_attr } = req.body;
    if (!g_id || !g_count || !g_attr) {
        return;
    }
    console.log(g_id, g_count, g_attr);
    let flag = await isGoodExist(uid, g_id, g_attr);
    console.log("flag：" + flag);

    let sql = "insert into user_cart values(null,?,?,?,?)";
    let params = [uid, g_id, g_count, g_attr];
    let result = null;
    let data = {
        code: 200,
        message: "商品已加入购物车",
        color: "#1e1e1e"
    }
    if (!flag) { //当前加入购物车商品不存在
        result = await dbUtil.asyncQuery(sql, params);
        if (!result) {
            data = {
                code: 400,
                message: "加入购物车失败",
                color: "red"
            }
        }
        console.log(data);
    } else { //存在
        sql = "update user_cart set g_count=g_count+? where g_id=? and current_g_attr=? and user_id=?";
        params = [g_count, g_id, g_attr, uid];
        result = await dbUtil.asyncQuery(sql, params);
        if (!result) {
            data = {
                code: 400,
                message: "加入购物车失败",
                color: "red"
            }
        }
        console.log(data);
    }
    res.send(data);
}

//判断购物是否已经存在某一商品
function isGoodExist(uid, g_id, g_attr) {
    let sql = "select * from user_cart where user_id=? and g_id=? and current_g_attr=?";
    let params = [uid, g_id, g_attr];
    return new Promise((resolve, reject) => {
        dbUtil.query(sql, params, (err, result) => {
            if (err) {
                reject(err.message);
            } else {
                if (result.length > 0) {
                    resolve(true); //购物车当前商品存在
                } else {
                    resolve(false); // 不存在
                }
            }
        })
    });
}

//用户信息
async function getUserInfo(req, res) {
    !req.session.currentUser && res.send({ code: 400, adminInfo: '' });
    let { uid } = req.session.currentUser;
    let sql = "select * from users where user_id=?";
    let params = [uid];
    let result = await dbUtil.asyncQuery(sql, params);
    if (result.length > 0) {
        delete result[0].user_pwd;
        if (result[0].user_role == "normal" && result[0].user_state == "Y") {
            res.send({ code: 200, userInfo: result[0] });
        }
    }
}


module.exports = {
    doIndex,
    doSearch,
    doGoodInfo,
    doAddCart,
    getUserInfo
}